import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortWordsAndWriteToFile {
    public static void main(String[] args) {
        String filePath = "file2.txt"; // 替换为您的文件路径

        try {
            List<String> words = readWordsFromFile(filePath);
            sortWords(words);
            writeWordsToFile(filePath, words);
            System.out.println("Words sorted and written back to file.");
        } catch (IOException e) {
            System.err.println("Error processing file: " + e.getMessage());
        }
    }

    private static List<String> readWordsFromFile(String filePath) throws IOException {
        List<String> words = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] lineWords = line.split("\\s+");
                for (String word : lineWords) {
                    if (!word.isEmpty()) {
                        words.add(word);
                    }
                }
            }
        }
        return words;
    }

    private static void sortWords(List<String> words) {
        Collections.sort(words, new Comparator<String>() {
            @Override
            public int compare(String word1, String word2) {
                return word1.compareToIgnoreCase(word2);
            }
        });
    }

    private static void writeWordsToFile(String filePath, List<String> words) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String word : words) {
                writer.write(word);
                writer.newLine(); // 添加换行符
            }
        }
    }
}
